//
//  UserInfo_Controller.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 15/11/10.
//  Copyright © 2015年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "UserInfo_Controller.h"
#define key_imageName @"key_imageName"
#define key_subtitle @"key_subtitle"
#define kVSpace 15
//vendor
#import "RDVTabBarController.h"
//untils
#import "UIColor+Hex.h"
#import "Global.h"
#import "ManagerGlobeUntil.h"
#import "AppDelegate.h"
//view
#import "TitleValueMoreCell.h"
#import "TitleRImageMoreCell.h"

//controllers
#import "RegisterOneStepViewController.h"
#import "ReSetNicknameController.h"
#import "MTA.h"
@interface UserInfo_Controller ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate,UIScrollViewDelegate>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *dataSource;
@end

@implementation UserInfo_Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#efefef"];
    _dataSource = [[NSMutableArray alloc]init];
    self.title = @"我的账户";
    [self addBackNavItem];
    [self setupSubView];
    [self initDataSource];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:YES animated:NO];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    AppDelegate *appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;
    [appDelegate.tabBarController setTabBarHidden:NO animated:YES];
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [MTA trackPageViewBegin:@"我的账户"];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [MTA trackPageViewEnd:@"我的账户"];
}
#pragma mark -- 初始化子视图
- (void)setupSubView {
    
    UIButton *quitLoginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [quitLoginButton setTitle:@"退出当前账户" forState:UIControlStateNormal];
    quitLoginButton.titleLabel.font = [UIFont systemFontOfSize:FontSize(17)];
    quitLoginButton.frame = CGRectMake(15, 0, self.view.bounds.size.width - 30, 44);
    UIImage *loginImage = [UIImage imageNamed:@"login_Btn"];
    loginImage = [loginImage stretchableImageWithLeftCapWidth:6 topCapHeight:6];
    [quitLoginButton setBackgroundImage:loginImage forState:UIControlStateNormal];
    [quitLoginButton addTarget:self action:@selector(quitLoginEvent) forControlEvents:UIControlEventTouchUpInside];
    
    UIView *footView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 44)];
    [footView addSubview:quitLoginButton];
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0
                                                             , 0
                                                             , CGRectGetWidth(self.view.bounds)
                                                              , CGRectGetHeight(self.view.bounds) - 64)
                                             style:UITableViewStylePlain];
    _tableView.delegate = (id<UITableViewDelegate>)self;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.dataSource = (id<UITableViewDataSource>)self;
    [_tableView registerClass:[TitleValueMoreCell class] forCellReuseIdentifier:kCellIdentifier_TitleValueMore];
    [_tableView registerClass:[TitleRImageMoreCell class] forCellReuseIdentifier:kCellIdentifier_TitleRImageMore];
    _tableView.tableFooterView = footView;
    
    [self.view addSubview:_tableView];
}

- (void)initDataSource {
    NSMutableArray *sectionArr = [[NSMutableArray alloc]init];
    
    //第一分区
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:self.userImage forKey:key_imageName];
    [dic setObject:@"" forKey:key_subtitle];
    [dic setObject:@"头像" forKey:@"title"];
    [sectionArr addObject:dic];
    
    
    dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@"" forKey:key_imageName];
    [dic setObject:self.userName forKey:key_subtitle];
    [dic setObject:@"用户名" forKey:@"title"];
    [sectionArr addObject:dic];
    
    
    dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@"" forKey:key_imageName];
    NSString *title = self.userPhoneNum;
    [dic setObject:title forKey:key_subtitle];
    [dic setObject:@"绑定手机号" forKey:@"title"];
    [sectionArr addObject:dic];
    
    
    dic = [[NSMutableDictionary alloc]init];
    [dic setObject:@"" forKey:key_imageName];
    [dic setObject:@"" forKey:key_subtitle];
    [dic setObject:@"修改账户密码" forKey:@"title"];
    [sectionArr addObject:dic];
    
    [self.dataSource addObject:sectionArr];
    
}
#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.dataSource objectAtIndex:section] count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dataDic = [[self.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    if (indexPath.section == 0 && indexPath.row == 0) {//用户头像cell
        TitleRImageMoreCell *imageCell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_TitleRImageMore forIndexPath:indexPath];
        if (imageCell == nil) {
            imageCell = [[TitleRImageMoreCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier_TitleRImageMore];
           
        }
         imageCell.selectionStyle = UITableViewCellSelectionStyleNone;
        imageCell.title = [dataDic objectForKey:@"title"];
        imageCell.userImage = [dataDic objectForKey:key_imageName];
        return imageCell;
       
    } else {//公共cell
        TitleValueMoreCell *commonCell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_TitleValueMore forIndexPath:indexPath];
        if (commonCell == nil) {
            commonCell = [[TitleValueMoreCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kCellIdentifier_TitleValueMore];
           
        }
        if (indexPath.section==0 &&(indexPath.row==1||indexPath.row==2)) {
             commonCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }

        if(indexPath.section == 0 && (indexPath.row == 1 || indexPath.row == 2)) {
            commonCell.accessoryType = UITableViewCellAccessoryNone;
        }
        [commonCell setTitleStr:[dataDic objectForKey:@"title"] valueStr:[dataDic objectForKey:key_subtitle]];
        return commonCell;
    }
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return HightScalar(72);
        } else {
            return HightScalar(54);
        }
    }
    return HightScalar(54);
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return HightScalar(15);
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat sectionHeaderHeight = HightScalar(15);
    if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
    else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
        scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == 0) {
        return 30;
    }
    return 1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [_tableView deselectRowAtIndexPath:indexPath animated:YES];

  // __weak typeof(self) weakSelf = self;
    if (indexPath.section == 0 && indexPath.row == 0) {//用户头像cell
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"更换头像" delegate:(id<UIActionSheetDelegate>)self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择", nil];
        [actionSheet showInView:self.view];
    } else if (indexPath.section == 0 && indexPath.row == 1) {//修改昵称
//       __block NSDictionary *dataDic = [[weakSelf.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
//        ReSetNicknameController *resetNicknameVC = [ReSetNicknameController settingTextVCWithTitle:@"修改用户名" textValue:[dataDic objectForKey:key_subtitle] doneBlock:^(NSString *textValue) {
//           // NSString *preValue = @"abc123";
////            dataDic = [[weakSelf.dataSource objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
////            [dataDic setValue:textValue forKey:key_subtitle];
////            [weakSelf.tableView reloadData];
//        }];
//        [self.navigationController pushViewController:resetNicknameVC animated:YES];
    }  else if (indexPath.section  == 0 && indexPath.row == 3 ) {//修改账号密码
               RegisterOneStepViewController *registerVC = [[RegisterOneStepViewController alloc]init];
        registerVC.typeOfView = OneStepIsModifiedPassword;
        [self.navigationController pushViewController:registerVC animated:YES];
    } else if (indexPath.section  == 0 && indexPath.row == 2 ) {//绑定手机号
//        RegisterOneStepViewController *registerVC = [[RegisterOneStepViewController alloc]init];
//        registerVC.typeOfView = OneStepIsModifiedPhoneNum;
//        [self.navigationController pushViewController:registerVC animated:YES];
        
    }
    
}

#pragma mark UIActionSheetDelegate M
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 2) {
        return;
    }
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    picker.allowsEditing = YES;//设置可编辑
    
    if (buttonIndex == 0) {
        //        拍照
//        if (![Helper checkCameraAuthorizationStatus]) {
//            return;
//        }
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    }else if (buttonIndex == 1){
        //        相册
//        if (![Helper checkPhotoLibraryAuthorizationStatus]) {
//            return;
//        }
        picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    }
    [self presentViewController:picker animated:YES completion:nil];//进入照相界面
    
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:^{
        UIImage *editedImage, *originalImage;
        editedImage = [info objectForKey:UIImagePickerControllerEditedImage];
       
        NSDictionary *dataDic = [[self.dataSource objectAtIndex:0] objectAtIndex:0];
        [dataDic setValue:editedImage forKey:key_imageName];
        [self.tableView reloadData];
        
        // 保存原图片到相册中
        if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
            originalImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            UIImageWriteToSavedPhotosAlbum(originalImage, self, nil, NULL);
        }
    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark -- button Aciotn
- (void)quitLoginEvent {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否退出账户?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.tag=2;
    [alert show];
    
    
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
        if (buttonIndex == 1){
            [[ManagerGlobeUntil sharedManager] clearUserInfoData];
            [self.navigationController popViewControllerAnimated:YES];
        }
}
-(void)backBtnAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
